<?php

namespace Api\Controller;

use Common\Controller;

class ShopsController extends Controller\ApiController {

    function searchShops() {
        $key = I('keyword', '', 'trim');
        $lable_id = I('label_id');
        if (emptys($key . $lable_id)) {
            $this->error('请输入搜索关键词');
        }

        $city_id = $this->getCityId();
        $cache_key = 'search_' . md5($key) . $lable_id . $city_id;
        $list = S($cache_key);
        if (!$list) {
            if (!emptys($lable_id)) {
                $lable_id = explode(',', trim($lable_id, ','));
                $lable_id = array_unique($lable_id); //去重
                $lable_id = array_slice($lable_id, 0, 5); // 最多5个标签
                $lable_id = implode(',', $lable_id);
                $map['_string'] = "s.category_id IN ($lable_id) OR s.taste IN ($lable_id)";
            }
            $where['s.name'] = array('like', "%$key%");
            $where['b.name'] = array('like', "%$key%");
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
            $map['city_id'] = $city_id;
            $list = M('Shops')->alias('s')->field('s.name as business_name,b.name as shop_name,s.id as shop_id')->order('s.create_time desc')->where($map)->join('LEFT JOIN __BUSINESS__ as b ON    b.id=s.business_id  AND b.status=1')->select();
            s($cache_key, $list, 300);
        }
        $this->output($list);
    }

    function addSearchRecord() {
        $key = I('keyword', '', 'trim');
        if (emptys($key)) {
            $this->error('请输入搜索关键词');
        }
        //登录后记录搜索历史记录
        $user_info = $this->getUserInfo();
        if ($user_info) {
            D('User')->addSearchRecord($user_info['user_id'], $key);
        }
        $this->success();
    }

    function getShopIsUserGiving() {
        $shop_id = (int) I('shop_id');
        $user_info = $this->getUserInfo();
        $data = array(
            'is_giving' => 0
        );
        if ($user_info) {
            $result = D('Shops')->isGivingShop($user_info['user_id'], $shop_id);
            if ($result)
                $data['is_giving'] = 1;
        }
        $this->output($data);
    }

    function addShopUserGiving() {

        $shop_id = (int) I('request.shop_id');
        $user_info = $this->getUserInfo();
        $is_cancel = I('request.is_cancel'); //取消赞
        if ($user_info) {
            if ($is_cancel == '1')
                $result = D('Shops')->delGivingShop($user_info['user_id'], $shop_id);
            else
                $result = D('Shops')->addGivingShop($user_info['user_id'], $shop_id);
        }

        if ($result)
            $this->success();
        else
            $this->error('服务器繁忙,请从新尝试');
    }

    function getShopsCouponList() {
        $shop_id = (int) I('shop_id');
        $cache_key = 'shop_coupon_info_' . $shop_id;
        $lat = I('lat');
        $lon = I('lon');

        $list = S($cache_key);
        if (!$list) {
            $label_list = array();
            $shop_info = D('Shops')->getNormalShopInfo($shop_id);

            if (!$shop_info)
                $this->error('该店铺不存在或者已下架');
            $where = array();
            $where['shop_id'] = $shop_id;
            $where['status'] = 1;
            $where['show_type'] = 1;
            $coupon_list = M('Coupon')->field('create_time', true)->where($where)->select();

            $category_name = getLabelNameById($shop_info['category_id']);
            $taste_name = getLabelNameById($shop_info['taste']);
            if (!emptys($category_name))
                $label_list[] = $category_name;
            if (!emptys($taste_name))
                $label_list[] = $taste_name;
            if (!emptys($shop_info['tag']))
                $label_list = array_merge($label_list, explode(',', trim($shop_info['tag'])));
            $shop_info['label_list'] = $label_list;
            $field = "business_name,name,image,up_count,longitude,latitude,business_start_time,business_end_time,label_list,ave_price,address,telephone";
            $list = array(
                'shop_info' => getArrayToKey(array($shop_info), $field)[0],
                'coupon_list' => $coupon_list,
            );
            S($cache_key, $list, 300);
        }
        if (is_numeric($lat) && is_numeric($lon) && is_array($list['shop_info'])) {
            $juli = GetDistance($lon, $lat, $list['shop_info']['longitude'], $list['shop_info']['latitude']);
            $list['shop_info']['juli'] = round($juli, 3);
        }
        $this->output($list);
    }

    function viewShop() {

        $shop_id = (int) I('id');
        if ($shop_id <= 0)
            $this->error('error');
        $user_ip = get_client_ip();
        $cache_key = "VIEW_SHOP_{$shop_id}_$user_ip";
        if (S($cache_key))
            $this->success();
        M('Shops')->where(array('id' => $shop_id))->setInc('view_num');
        $time = strtotime(date('Ymd23:59:59')); //一个IP一天只算一次
        S($cache_key, true, $time - time());
        $this->success();
    }

    function getShopsUserCouponList() {
        $shop_id = (int) I('shop_id');
        $cache_key = 'shop_user_coupon_info_' . md5($shop_id);
        $lat = I('lat');
        $lon = I('lon');
        $list = S($cache_key);
        if (!$list) {
            $label_list = array();
            $shop_info = D('Shops')->getNormalShopInfo($shop_id);

            if (!$shop_info)
                $this->error('该店铺不存在或者已下架');
            $where = array();
            $where['shop_id'] = $shop_id;
            $where['status'] = 1;
            $where['show_type'] = 1;

            $model = M('CouponList');

            $sql = $model->order('id desc')->select(false);

            $coupon_list = $model->query("SELECT l.remark,l.user_id,l.coupon_code,l.id,c.discount,c.start_time,c.expired_time FROM ($sql) as l  LEFT JOIN __COUPON__ as c ON c.id=l.coupon_id WHERE l.shops_id=$shop_id AND l.status=3 GROUP BY l.coupon_code ORDER BY l.id desc");

            $coupon_list = is_array($coupon_list) ? $coupon_list : array();

            foreach ($coupon_list as &$info) {
                $info['remark'] = (string) $info['remark'];
                $info['user_name'] = (string) $this->getUserExInfo($info['user_id'])['nickname'];
                $info['coupon_code'] = couponEDC($info['coupon_code']);
                $info['credit'] = (string) getReceiveCredit($info['discount']);
                unset($info['user_id']);
            }
            $category_name = getLabelNameById($shop_info['category_id']);
            $taste_name = getLabelNameById($shop_info['taste']);
            if (!emptys($category_name))
                $label_list[] = $category_name;
            if (!emptys($taste_name))
                $label_list[] = $taste_name;
            if (!emptys($shop_info['tag']))
                $label_list = array_merge($label_list, explode(',', trim($shop_info['tag'])));
            $shop_info['label_list'] = $label_list;
            $field = "business_name,name,image,up_count,longitude,latitude,business_start_time,business_end_time,label_list,ave_price,address,telephone";
            $list = array(
                'shop_info' => getArrayToKey(array($shop_info), $field)[0],
                'coupon_list' => $coupon_list,
            );
            S($cache_key, $list, 300);
        }
        if (is_numeric($lat) && is_numeric($lon) && is_array($list['shop_info'])) {
            $juli = GetDistance($lon, $lat, $list['shop_info']['longitude'], $list['shop_info']['latitude']);
            $list['shop_info']['juli'] = round($juli, 3);
        }
        $this->output($list);
    }

    function getShopExInfo() {
        $shop_id = I('shop_id');
        $coupon_id = I('coupon_id');

        if (!emptys($shop_id)) {
            $id = $shop_id;
            $id = explode(',', $id);
            $where = array(
                'id' => array('in', $id),
            );
            $result = M('shops')->where($where)->field('id,up_count')->select();
            $result = array_cc($result, 'id');
        } else if (!emptys($coupon_id)) {
            $id = $coupon_id;
            $id = explode(',', $id);
            $where = array(
                'id' => array('in', $id),
            );
            $result = M('coupon')->where($where)->field('id,coupon_count,for_count')->select();
            $result = array_cc($result, 'id');
        } else {
            $result = array();
        }


        $this->output($result);
    }

}
